package com.dvt.faceScan;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

import com.dvt.faceScan.httpUntil.XmlRpcUtils;
import com.dvt.faceScan.widget.Config;
import com.dvt.faceScan.widget.CustomDatePicker;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;


public class KqglActivity extends Activity implements View.OnClickListener {
    private TextView tv1;//item.xml里的TextView：Textviewname
    private TextView tv2;//item.xml里的TextView：Textviewage
    private TextView tvStartDate;//item.xml里的TextView：Textviewage
    private TextView tvEndDate;//item.xml里的TextView：Textviewage
    private Button btn_startDate;
    private Button btn_endDate;

    private ListView lv;//activity_main.xml里的ListView
    private BaseAdapter adapter;//要实现的类
    private ArrayList<employeeModel> gzList = new ArrayList<employeeModel>();//实体类

    private String now_date;
    private String start_date;
    private String end_date;

    private CustomDatePicker customDatePicker1, customDatePicker2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.kqgl_activity);

        lv = (ListView) findViewById(R.id.listView4);
        tvStartDate = (TextView) findViewById(R.id.Tv_startDate);
        tvEndDate = (TextView) findViewById(R.id.Tv_endDate);
        btn_startDate = (Button) findViewById(R.id.Btn_startdate);
        btn_endDate = (Button) findViewById(R.id.Btn_enddate);
        btn_startDate.setOnClickListener(this);
        btn_endDate.setOnClickListener(this);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        now_date = df.format(new Date()).toString();// new Date()为获取当前系统时间

        initDatePicker();

        requestKqxxDetail();

        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return gzList.size();//数目
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = KqglActivity.this.getLayoutInflater();
                View view;

                if (convertView == null) {
                    //因为getView()返回的对象，adapter会自动赋给ListView
                    view = inflater.inflate(R.layout.item_xzgs, null);
                } else {
                    view = convertView;
                    Log.i("info", "有缓存，不需要重新生成" + position);
                }
                tv1 = (TextView) view.findViewById(R.id.Textviewgs);//找到Textviewname
                tv1.setText(gzList.get(position).getCompany());//设置参数

                tv2 = (TextView) view.findViewById(R.id.Textviewgo2);//找到Textviewage
                tv2.setText(gzList.get(position).getSalary() + " " + "人/次");//设置参数
                tv2.setTextColor(Color.RED);

                return view;
            }

            @Override
            public long getItemId(int position) {//取在列表中与指定索引对应的行id
                return 0;
            }

            @Override
            public Object getItem(int position) {//获取数据集中与指定索引对应的数据项
                return null;
            }
        };
        lv.setAdapter(adapter);


        //获取当前ListView点击的行数，并且得到该数据
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv1 = (TextView) view.findViewById(R.id.Textviewgs);//找到Textviewname
                String str = tv1.getText().toString();//得到数据
                //Toast.makeText(Gzcx.this, "点击..." + str, Toast.LENGTH_SHORT).show();//显示数据

                //跳转页面

            }
        });


    }

    @Override
    public void onClick(View v) {
        if (btn_startDate == v) {
            customDatePicker1.show(now_date);
        }
        if (btn_endDate == v) {
            customDatePicker2.show(now_date);
        }
    }

    //考勤信息查询
    public void requestKqxxDetail() {
        Callable<String> c = new Callable<String>() {
            @Override
            public String call() throws ParseException {
                int uid = 1;
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = "dris.employee_attendance";
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 683;

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("action", action_id);
                Map<String, Object> context = new HashMap<String, Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("group_by", "hired_company_id");
                context.put("params", params);

                start_date = tvStartDate.getText().toString() + " 00:00:00";
                end_date = tvEndDate.getText().toString() + " 23:59:59";

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse(start_date);
                long start_rightTime = (long) (date.getTime() - 8 * 60 * 60 * 1000); //把当前得到的时间用date.getTime()的方法写成时间戳的形式，再加上8小时对应的毫秒数
                String new_start_date = sdf.format(start_rightTime);//把得到的新的时间戳再次格式化成时间的格式

                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date2 = sdf.parse(end_date);
                long end_rightTime = (long) (date2.getTime() - 8 * 60 * 60 * 1000);
                String new_end_date = sdf.format(end_rightTime);

                Log.d("wumh_debug", "时间:" + new_start_date + "|" + new_end_date);

                List domain = asList("&", asList("sign_in", ">=", new_start_date), asList("sign_out", "<=", new_end_date));

                List args = new ArrayList();

                List groupby = asList("hired_company_id");

                List fields = asList("hired_company_id", "employee_name");

                Map<String, Object> kwargs = new HashMap<String, Object>();
                kwargs.put("context", context);
                kwargs.put("groupby", groupby);
                kwargs.put("fields", fields);
                kwargs.put("limit", 80);
                kwargs.put("domain", domain);

                Object requestObj = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model, "read_group", args, kwargs));
                List r = asList((Object[]) requestObj);
                for (Object object : r) {
                    Map<String, Object> a = (HashMap) object;
                    employeeModel employee = new employeeModel();

                    Object[] o = (Object[]) a.get("hired_company_id");
                    List<Object> ol = asList(o);
                    employee.setCompany(ol.get(1).toString());
                    employee.setSalary(a.get("hired_company_id_count").toString());

                    Set<String> akeySet = a.keySet();
                    for (String key : akeySet) {
                        Log.d("mmmmmmmm", key + "-->" + a.get(key));
                    }
                    gzList.add(employee);
                }
                return "";

            }
        };

        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try {
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        tvStartDate.setText(now.split(" ")[0]);
        //currentTime.setText(now);
        tvEndDate.setText(now.split(" ")[0]);
        customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tvStartDate.setText(time.split(" ")[0]);
                gzList = new ArrayList<employeeModel>();
                requestKqxxDetail();
                adapter.notifyDataSetChanged();
                lv.setAdapter(adapter);
            }
        }, "1970-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(false); // 不显示时和分
        customDatePicker1.setIsLoop(false); // 不允许循环滚动

        customDatePicker2 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tvEndDate.setText(time.split(" ")[0]);
                gzList = new ArrayList<employeeModel>();
                requestKqxxDetail();
                adapter.notifyDataSetChanged();
                lv.setAdapter(adapter);
            }
        }, "1970-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker2.showSpecificTime(false); // 不显示时和分
        customDatePicker2.setIsLoop(false); // 不允许循环滚动

//        customDatePicker2 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
//            @Override
//            public void handle(String time) { // 回调接口，获得选中的时间
//                tvEndDate.setText(time);
//            }
//        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
//        customDatePicker2.showSpecificTime(false); // 显示时和分
//        customDatePicker2.setIsLoop(true); // 允许循环滚动
    }

    private List asList(Object... a) {
        return Arrays.asList(a);
    }


}